package com.cpr.core.rabbitmq.springctl.anno.config;

import com.cpr.core.rabbitmq.springctl.anno.MyMessageListener;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.net.URI;

/**
 * @author Chen Panrui
 * created at 2022/3/16 0:26
 */
@Configuration
@EnableRabbit
@Import(MyMessageListener.class)
public class RabbitConsumerListenerConfig {

    @Bean
    public ConnectionFactory connectionFactory(){
        // 这个接口下面有几个 实例，可以看下
        return new CachingConnectionFactory(URI.create("amqp://admin:123456@106.13.89.7:5672/%2f"));
    }

    @Bean
    @Autowired
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        return new RabbitTemplate(connectionFactory);
    }

    @Bean
    @Autowired
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public Queue queue(){
        return QueueBuilder.nonDurable("queue.anno").build();
    }

    @Bean("rabbitListenerContainerFactory")
    @Autowired
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
        // 设置了 并发消费和批次 会影响消费的顺序
        // 可以有10个并发的消费者消费
        factory.setConcurrentConsumers(10);
        factory.setMaxConcurrentConsumers(15);
        // 消息可以分批次推送过来，一个批次10个
        factory.setBatchSize(10);
        return factory;
    }

}
